/**
 * 该文件用于验证token
 * 结合passport与passport-jwt
 */

const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const secretOrKey = require("../config/keys.js").secretOrKey;
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = secretOrKey;

const mongoose = require("mongoose");
const UserModel = mongoose.model("users");

module.exports = (passport) => {
    passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
        // console.log("============", jwt_payload);
        //这个jwt_payload就是登录时存jwt的用户信息对象--即前面user.js里面的rule
        UserModel.findById(jwt_payload.id).then((doc) => {
            if (doc) {
                done(null, doc, "查询有数据");
            } else {
                done(null, false, "查询无数据");
            };
        }).catch((err) => {
            console.log(err);
            done(null, {
                message: "token验证出错"
            });
        });
    }));
};